import { $url } from '@/api';

export function uploadAvatar() {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        uni.uploadFile({
          url: `${$url}/common/upload`, // 上传接口地址
          filePath: res.tempFilePaths[0], // 文件路径
          name: 'file', // 文件字段名
          header: {
            Authorization: `Bearer ${uni.getStorageSync('token')}`, // Token (如果需要)
          },
          success: (res) => {
            const response = JSON.parse(res.data); // uni.uploadFile 返回的 res.data 是字符串
            if (response.code === 200) {
              uni.showToast({
                title: '上传成功',
              });
              resolve(response);
            }
            else {
              uni.showToast({
                title: '上传失败',
              });
              reject(new Error(response.message || '上传失败'));
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}
